// pages/history/history.js
const app = getApp()

Page({
  data: {
    history: [],
    filteredHistory: [],
    totalRecords: 0,
    highRiskCount: 0,
    mediumRiskCount: 0,
    lowRiskCount: 0,
    
    // 应用信息
    appInfo: {},
    
    // 筛选选项
    filterOptions: [
      { value: 'all', label: '全部记录' },
      { value: 'high', label: '高风险' },
      { value: 'medium', label: '中风险' },
      { value: 'low', label: '低风险' },
      { value: 'camera', label: '镜头检测' },
      { value: 'wifi', label: 'WiFi扫描' },
      { value: 'magnetic', label: '磁场检测' },
      { value: 'combined', label: '综合检测' }
    ],
    filterIndex: 0,
    
    // 排序选项
    sortOptions: [
      { value: 'time_desc', label: '时间降序' },
      { value: 'time_asc', label: '时间升序' },
      { value: 'risk_desc', label: '风险降序' },
      { value: 'risk_asc', label: '风险升序' }
    ],
    sortIndex: 0,
    
    // 详情弹窗
    showDetail: false,
    selectedRecord: null,
    
    // 其他弹窗
    showFeedbackModal: false,
    showAboutModal: false,
    
    // 方法名称映射
    methodNames: {
      camera: '镜头检测',
      wifi: 'WiFi扫描',
      magnetic: '磁场检测',
      combined: '综合检测'
    },
    
    // 风险等级映射
    riskLevelMap: {
      low: '低风险',
      medium: '中风险',
      high: '高风险'
    }
  },

  onLoad() {
    this.setData({
      appInfo: app.globalData.appInfo
    })
    this.loadHistory()
  },

  onShow() {
    this.loadHistory()
  },

  // 加载历史记录
  loadHistory() {
    const history = wx.getStorageSync('detection_history') || []
    
    // 处理数据格式
    const processedHistory = history.map(record => {
      const formatTime = app.utils.formatTime(new Date(record.timestamp))
      const riskText = this.data.riskLevelMap[record.riskLevel] || '未知'
      
      // 获取使用的检测方法
      const methods = []
      if (record.result.camera) methods.push('camera')
      if (record.result.wifi) methods.push('wifi')
      if (record.result.magnetic) methods.push('magnetic')
      if (record.detectType === 'combined') methods.push('combined')
      
      // 格式化检测时长
      let formatDuration = ''
      if (record.result.camera && record.result.camera.duration) {
        const duration = Math.floor(record.result.camera.duration / 1000)
        formatDuration = `${Math.floor(duration / 60)}分${duration % 60}秒`
      }
      
      return {
        ...record,
        formatTime,
        riskText,
        methods,
        methodNames: this.data.methodNames,
        formatDuration
      }
    })
    
    // 统计数据
    const stats = this.calculateStats(processedHistory)
    
    this.setData({
      history: processedHistory,
      ...stats
    })
    
    // 应用筛选和排序
    this.applyFilterAndSort()
  },

  // 计算统计数据
  calculateStats(history) {
    const stats = {
      totalRecords: history.length,
      highRiskCount: 0,
      mediumRiskCount: 0,
      lowRiskCount: 0
    }
    
    history.forEach(record => {
      switch (record.riskLevel) {
        case 'high':
          stats.highRiskCount++
          break
        case 'medium':
          stats.mediumRiskCount++
          break
        case 'low':
          stats.lowRiskCount++
          break
      }
    })
    
    return stats
  },

  // 应用筛选和排序
  applyFilterAndSort() {
    let filtered = [...this.data.history]
    
    // 应用筛选
    const filterValue = this.data.filterOptions[this.data.filterIndex].value
    if (filterValue !== 'all') {
      if (['high', 'medium', 'low'].includes(filterValue)) {
        // 按风险等级筛选
        filtered = filtered.filter(record => record.riskLevel === filterValue)
      } else {
        // 按检测方法筛选
        filtered = filtered.filter(record => 
          record.detectType === filterValue || record.methods.includes(filterValue)
        )
      }
    }
    
    // 应用排序
    const sortValue = this.data.sortOptions[this.data.sortIndex].value
    filtered.sort((a, b) => {
      switch (sortValue) {
        case 'time_desc':
          return b.timestamp - a.timestamp
        case 'time_asc':
          return a.timestamp - b.timestamp
        case 'risk_desc':
          return this.getRiskScore(b.riskLevel) - this.getRiskScore(a.riskLevel)
        case 'risk_asc':
          return this.getRiskScore(a.riskLevel) - this.getRiskScore(b.riskLevel)
        default:
          return 0
      }
    })
    
    this.setData({
      filteredHistory: filtered
    })
  },

  // 获取风险等级分数（用于排序）
  getRiskScore(riskLevel) {
    switch (riskLevel) {
      case 'high': return 3
      case 'medium': return 2
      case 'low': return 1
      default: return 0
    }
  },

  // 筛选改变
  onFilterChange(e) {
    this.setData({
      filterIndex: parseInt(e.detail.value)
    })
    this.applyFilterAndSort()
  },

  // 排序改变
  onSortChange(e) {
    this.setData({
      sortIndex: parseInt(e.detail.value)
    })
    this.applyFilterAndSort()
  },

  // 查看详情
  viewDetail(e) {
    const id = e.currentTarget.dataset.id
    const record = this.data.history.find(item => item.id === id)
    
    if (record) {
      this.setData({
        selectedRecord: record,
        showDetail: true
      })
    }
  },

  // 关闭详情
  closeDetail() {
    this.setData({
      showDetail: false,
      selectedRecord: null
    })
  },

  // 分享记录
  shareRecord(e) {
    const id = e.currentTarget.dataset.id
    const record = this.data.history.find(item => item.id === id)
    
    if (!record) return
    
    // 构建分享内容
    let shareText = `安心住助手检测报告\n`
    shareText += `时间: ${record.formatTime}\n`
    if (record.location) {
      shareText += `地点: ${record.location}\n`
    }
    shareText += `风险等级: ${record.riskText}\n`
    shareText += `检测方法: ${record.methods.map(m => this.data.methodNames[m]).join(', ')}\n`
    
    if (record.result.camera) {
      shareText += `镜头检测: 发现${record.result.camera.suspiciousPoints.length}个可疑点\n`
    }
    if (record.result.wifi) {
      shareText += `WiFi扫描: 发现${record.result.wifi.suspiciousDevices.length}个可疑设备\n`
    }
    if (record.result.magnetic) {
      shareText += `磁场检测: 发现${record.result.magnetic.anomalies.length}个异常点\n`
    }
    
    // 复制到剪贴板
    wx.setClipboardData({
      data: shareText,
      success: () => {
        wx.showToast({
          title: '已复制到剪贴板',
          icon: 'success'
        })
      }
    })
  },

  // 删除记录
  deleteRecord(e) {
    const id = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条检测记录吗？',
      success: (res) => {
        if (res.confirm) {
          // 从存储中删除
          const history = wx.getStorageSync('detection_history') || []
          const newHistory = history.filter(item => item.id !== id)
          wx.setStorageSync('detection_history', newHistory)
          
          // 重新加载数据
          this.loadHistory()
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
        }
      }
    })
  },

  // 跳转到检测页面
  goToDetection() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadHistory()
    wx.stopPullDownRefresh()
  },

  // 反馈建议
  onFeedback() {
    this.setData({
      showFeedbackModal: true
    })
  },

  // 关闭反馈弹窗
  closeFeedbackModal() {
    this.setData({
      showFeedbackModal: false
    })
  },

  // 复制邮箱
  copyEmail() {
    wx.setClipboardData({
      data: 'shalei@sentxi.com',
      success: () => {
        wx.showToast({
          title: '邮箱已复制',
          icon: 'success'
        })
        this.closeFeedbackModal()
      }
    })
  },

  // 复制微信号
  copyWechat() {
    wx.setClipboardData({
      data: 'shalei8980',
      success: () => {
        wx.showToast({
          title: '微信号已复制',
          icon: 'success'
        })
        this.closeFeedbackModal()
      }
    })
  },

  // 查看全部记录
  viewAllRecords() {
    // 这里可以跳转到完整的历史记录页面，或者展开显示所有记录
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  },

  // 关于我们
  onAbout() {
    this.setData({
      showAboutModal: true
    })
  },

  // 关闭关于我们弹窗
  closeAboutModal() {
    this.setData({
      showAboutModal: false
    })
  },

  // 分享给好友
  onShareAppMessage() {
    const historyCount = this.data.filteredHistory.length
    const totalCount = this.data.detectionHistory.length
    
    return {
      title: `我的检测记录 (${totalCount}条) - 安心住助手`,
      desc: '查看我的隐私安全检测历史记录',
      path: '/pages/history/history'
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '检测历史记录 - 安心住助手',
      query: 'page=history'
    }
  }
})
